package com.czm.art_light.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.czm.art_light.annotation.CacheWithLock;
import com.czm.art_light.constant.ArtErrorCodeEnum;
import com.czm.art_light.constant.CommonConsts;
import com.czm.art_light.constant.RedisConstant;
import com.czm.art_light.entity.ArtArtist;
import com.czm.art_light.entity.ArtCategory;
import com.czm.art_light.entity.ArtTopic;
import com.czm.art_light.entity.ArtWork;
import com.czm.art_light.exception.BusinessException;
import com.czm.art_light.mapper.ArtArtistMapper;
import com.czm.art_light.mapper.ArtCategoryMapper;
import com.czm.art_light.mapper.ArtWorkMapper;
import com.czm.art_light.param.request.ArtInfoReqDto;
import com.czm.art_light.param.request.ArtWorkReqDto;
import com.czm.art_light.param.request.PageReqDto;
import com.czm.art_light.param.response.*;
import com.czm.art_light.service.ArtCategoryService;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 类别信息 服务类
 */
@Service
public class ArtCategoryServiceImpl implements ArtCategoryService {
    @Autowired
    private ArtCategoryMapper artCategoryMapper;

    @Autowired
    private ArtWorkMapper artWorkMapper;

    @Autowired
    private ArtArtistMapper artArtistMapper;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 根据类别id查找对应的类别信息
     */
    @CacheWithLock(
            cacheName = "artCategoryCache",
            key = "#artInfoReqDto.id + '::' + #artInfoReqDto.pageNum + '::' + #artInfoReqDto.pageSize",   //从参数对象提取属性
            expireTime = CommonConsts.CATEGORY_CACHE_EXPIRATION_TIME,
            cacheNull = true,
            enabled = true
    )
    @Override
    public ArtInfoRespDto getById(ArtInfoReqDto artInfoReqDto) {
        // 判断布隆过滤器中是否存在数据
        RBloomFilter<Integer> rBloomFilter = redissonClient.getBloomFilter(RedisConstant.ART_CATEGORY_BLOOM_FILTER_KEY);
        //不存在直接返回null
        if (!rBloomFilter.contains(artInfoReqDto.getId())) {
            return null;
        }

        ArtCategory artCategory = artCategoryMapper.getById(artInfoReqDto.getId());
        // 类别不存在
        if (artCategory == null) {
            throw new BusinessException(ArtErrorCodeEnum.CATEGORY_NOT_EXIST);
        }

        //构建分页对象
        Page<ArtWorkBasicInfoRespDto> page = new Page<>(artInfoReqDto.getPageNum(), artInfoReqDto.getPageSize());
        //根据类别id查找对应的艺术家
        ArtWorkReqDto artWorkReqDto = new ArtWorkReqDto();
        artWorkReqDto.setCategoryId(artInfoReqDto.getId());
        //根据类别id查找所有的艺术家id
        List<Integer> artistIdList = artWorkMapper.listArtArtistIdByParamId(page, artWorkReqDto);
        //再根据查找到的艺术家id查找对应的艺术家基本信息
        List<ArtArtistBasicInfoRespDto> artists = new ArrayList<>();
        if (!artistIdList.isEmpty()) {
            for (Integer id : artistIdList) {
                //根据艺术家id查找对应的艺术家基本信息
                ArtArtistBasicInfoRespDto artArtistBasicInfoRespDto = artArtistMapper.artistBasicInfogetById(id);
                artists.add(artArtistBasicInfoRespDto);
            }
        }

        //根据类别id查找对应的艺术作品数据
        List<ArtWork> workList = artWorkMapper.listArtWorkByParamId(page, artWorkReqDto);
        List<ArtWorkBasicInfoRespDto> artworks = new ArrayList<>();
        if (!workList.isEmpty()) {
            for (ArtWork work : workList) {
                artworks.add(ArtWorkBasicInfoRespDto.builder()
                        //作品id
                        .id(work.getId())
                        //作品名称
                        .title(work.getTitle())
                        //艺术家名称
                        .artistName(artArtistMapper.getById(work.getArtistId()).getArtistName())
                        //作品图片
                        .primaryImageSmallUrl(work.getPrimaryImageSmallUrl())
                        .build());
            }
        }

        return ArtInfoRespDto.builder()
                //类别id
                .id(artCategory.getId())
                //类别名称
                .name(artCategory.getCategoryName())
                //类别图片
                .imageUrl(artCategory.getBackgroundImageUrl())
                //话题简介
                .description(artCategory.getCategoryDescription())
                //艺术家列表
                .artists(artists)
                //艺术作品列表
                .artworks(artworks)
                .build();
    }

    /**
     * 获取所有的类别基本信息
     */
    @Override
    public List<ArtCategoryBasicInfoRespDto> list(PageReqDto pageReqDto) {
        List<ArtCategoryBasicInfoRespDto> artCategories = new ArrayList<>();

        if (pageReqDto.isFetchAll()) {
            // 如果 fetchAll 为 true，则查询所有数据，忽略分页
            List<ArtCategory> artCategoryList = artCategoryMapper.selectAllWithoutPage();
            for (ArtCategory artCategory : artCategoryList) {
                artCategories.add(ArtCategoryBasicInfoRespDto.builder()
                        //类别id
                        .id(artCategory.getId())
                        //类别名字
                        .categoryName(artCategory.getCategoryName())
                        .build());
            }
        } else {
            // 如果 fetchAll 为 false，则使用分页查询
            Page<ArtCategoryBasicInfoRespDto> page = new Page<>(pageReqDto.getPageNum(), pageReqDto.getPageSize());
            artCategories = artCategoryMapper.selectAll(page);
        }

        // 返回结果，如果无数据，返回空列表
        return artCategories == null ? Collections.emptyList() : artCategories;
    }
}
